package com.cb.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.entity.BuyList;
import com.cb.entity.InStore;
import com.cb.entity.Product;
import com.cb.mapper.BuyListMapper;
import com.cb.mapper.ProductMapper;
import com.cb.service.InStoreService;
import com.cb.mapper.InStoreMapper;
import com.cb.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class InStoreServiceImpl extends ServiceImpl<InStoreMapper, InStore> implements InStoreService{

    @Autowired
    private BuyListMapper buyListMapper;
    @Autowired
    private InStoreMapper inStoreMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result saveInStore(InStore inStore, Integer buyId) {
        //添加入库单
        boolean save = save(inStore);
        if(!save){
            return Result.err(Result.CODE_ERR_BUSINESS, "入库单添加失败！");
        }
        //根据id将采购单状态改为已入库
        LambdaUpdateWrapper<BuyList> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(BuyList::getIsIn,1).eq(BuyList::getBuyId,buyId);
        int update = buyListMapper.update(null, updateWrapper);
        if(update>0){
            return Result.ok("入库单添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "入库单添加失败！");
    }

    @Override
    public IPage<InStore> queryInStorePage(Page<InStore> inStorePage, InStore inStore) {
        return inStoreMapper.selectInStorePage(inStorePage,inStore);
    }

    @Override
    public Result confirmInStore(InStore inStore) {
        //根据id将入库单状态改为已入库
        LambdaUpdateWrapper<InStore> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(InStore::getIsIn,1).eq(InStore::getInsId,inStore.getInsId());
        int update = baseMapper.update(null, updateWrapper);
        if(update<=0){
            return Result.err(Result.CODE_ERR_BUSINESS, "入库失败！");
        }
        //根据商品id增加商品库存
        LambdaUpdateWrapper<Product> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.eq(Product::getProductId,inStore.getProductId())
                .setSql("product_invent=product_invent+"+inStore.getInNum());
        int update1 = productMapper.update(null, updateWrapper1);
        if(update1>0){
            return Result.ok("入库成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "入库失败！");
    }
}




